#include "gbk.h"

#include<string>

using namespace std;

void EraseChar(string &line, const char chr)
{
	size_t found = 0;
	while(1)
	{
		found = line.find(chr, found);
		if(found != string::npos) line.erase(found, 1);
		else break;
	}
}

void SplitByChar(str_bucket_t& bucket, const string &line, const char chr)
{
	const char * txt;
	size_t found = 0;
	size_t lastfound = 0;
	while(1)
	{
		lastfound = found;
		found = line.find(chr, found);
		if(found == lastfound) 
		{
			found++;
			continue;
		}
		if(found != string::npos)
		{
			txt = line.substr(lastfound, found-lastfound).c_str();	
			string sub(txt);
			if(sub != "") bucket.push_back(sub);
			found++;
		}
		else
		{
			txt = line.substr(lastfound, found-lastfound).c_str();	
			string sub(txt);
			if(sub != "") bucket.push_back(sub);
			break;
		}
	}
}

string GetGBKChar(const string& str, size_t pos)
{
	if(pos < 0 || pos > str.size()) return "";
	return str.substr(pos, ((str[pos] & (char)(0x80)) == 0) ? 1 : 2);
}

bool isGBK(const string& str)
{
	if(2 != str.size()) return false;
	return ( ((str[0] & 0x00FF) >= 0x00B0) && ((str[0] & 0x00FF) <= 0x00F7)
			&& ((str[1] & 0x00FF)>= 0x00A1) && ((str[1] & 0x00FF) <= 0x00FE) )
		? true : false;
}

string GetGBKString(const string& str, const size_t pos, const int len)
{
	size_t scan = pos;
	string buf = "";
	if(pos < 0 || pos > str.size()) return "";
	for(int i=0; i<len; i++)
	{
		string temp = GetGBKChar(str, scan);
		if( !isGBK(temp) )
		{
			buf = "";
			break;
		}
		buf = buf + temp;
		scan += temp.size();
		if(scan >= str.size()) break;
	}
	return buf;
}
